import React, { useEffect, useState,Component } from 'react'
import instance from '../../api/request'
import { Space, Table, Tag } from 'antd';
import { Button, Checkbox, Form, Input,Modal, message, Popconfirm ,Drawer  } from 'antd';
function Index() {
  // 文章详情
  
  // const [open, setOpen] = useState(false);
  // const [order,setOrder]=useState([])
  // const showDrawer = async (id) => {
  //   setOpen(true);
  //   const res = await instance.get(`/article/${id}`, {
  //     params: {
  //       id: id,
  //     },
  //   });
  //   setOrder(res.data)
  // };
  const [order,setOrder]=useState([])
   const [open, setOpen] = useState(false);
  const showDrawer = async(id) => {
    setOpen(true);
    const res=await instance.get(`/article/${id}`,{
      params:{
    id:id
      }
    })
    setOrder(res.data)
  };
    
  const onClose = () => {
    setOpen(false);
  };
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const onSelectChange = newSelectedRowKeys => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  // 批量删除
  const pl=()=>{
setSelectedRowKeys&&setSelectedRowKeys((item)=>{
  if(window.confirm('您确定要删除吗?')){

  setList(item.shanchu)
  }
 
})
  }
  // 删除
  const confirm = id => {
  console.log(id);
  message.success('删除成功');
  const shanchu=list.filter((v)=>v.id!=id)
  setList(shanchu)
};
const cancel = e => {
  console.log(e);
  message.error('Click on No');
};
  // 编辑
    const [addform] = Form.useForm();
  const [edit,setEdit]=useState()
   const bian=(record)=>{
      setIsModalOpen(true);
    setTitle('编辑')
    setEdit(record.id)
    addform.setFieldsValue({
      title:record.title,
      content:record.content
    })
   }
  // 新增
  const [title,setTitle]=useState()
 const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
    setTitle('新增')
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const Finish = values => {
  console.log('Success:', values);
  const commdata={
    title:values.title,//文章标题
content:values.content,//文章内容
tagList:values.tagList,//标签  array[string]
categoryList:values.categoryList,//分类  array[string]
authorId:47529555//用户id 暂时写死47529555 登陆成功后返回的用户信息
}
if(title=='新增'){
instance.post('/article',commdata,{
  headers : {
  Authorization:'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Imp5a2wiLCJ1c2VySWQiOjQ3NTI5NTU1LCJyb2xlIjoxLCJpYXQiOjE3Mzk3OTQyNDIsImV4cCI6MTc0MjM4NjI0Mn0.O7KlsogMjr6YowtOXKGrEaldz5kjKHWQCn3FGvRd1bA',
}

}).then((res)=>{
alert('新增成功')
setIsModalOpen(false);
getData()
})
}else{
  instance.put(`/article/${edit}`,commdata,{
      headers : {
  Authorization:'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Imp5a2wiLCJ1c2VySWQiOjQ3NTI5NTU1LCJyb2xlIjoxLCJpYXQiOjE3Mzk3OTQyNDIsImV4cCI6MTc0MjM4NjI0Mn0.O7KlsogMjr6YowtOXKGrEaldz5kjKHWQCn3FGvRd1bA',
}
  }).then((res)=>{
    alert('编辑成功')
    setIsModalOpen(false);
    getData()
  })
}

};
const FinishFailed = errorInfo => {
  console.log('Failed:', errorInfo);
};
  // 重置
  const [form] = Form.useForm();
  const qinchu=()=>{
form.resetFields('')
  }
// 搜索
const [keyword,setKeyword]=useState('')
const onFinish = values => {
  console.log('Success:', values);
setKeyword(values.keyword)
};
const onFinishFailed = errorInfo => {
  console.log('Failed:', errorInfo);
};
  // 渲染表格
  const [list,setList]=useState()
  const getData=()=>{
    instance.get('/article/list',{
      params:{
        keyword
      }
    }).then((res)=>{
      setList(res.data.rows)
    })
  }

  useEffect(()=>{
   getData()
  },[keyword])
  // 数据
  const columns = [
  {
    title: 'Id',
    dataIndex: 'id',
    key: 'id',
    render: text => <a>{text}</a>,
  },
  {
    title: '文章标题',
    dataIndex: 'title',
    key: 'title',
  },
  {
    title: '文章内容',
    dataIndex: 'content',
    key: 'content',
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
  },
  {
    title: '操作',
    key: 'action',
    render: (_, record) => (
      <Space size="middle">
        <Button onClick={()=>bian(record)}>编辑</Button>
        <Button onClick={()=>showDrawer(record.id)}>详情</Button>
   <Popconfirm
    title="Delete the task"
    description="你确定删除吗?"
    onConfirm={()=>confirm(record.id)}
    onCancel={cancel}
    okText="确定"
    cancelText="取消"
  >
    <Button danger>删除</Button>
  </Popconfirm>
      </Space>
    ),
  },
];
  return (
    <div>
      {/* 文章详情 */}
 <Drawer
        title="Basic Drawer"
        closable={{ 'aria-label': 'Close Button' }}
        onClose={onClose}
        open={open}
      >
     <p>文章内容：{order.title}</p>
      <p>文章标题：{order.content}</p>
      <p>文章时间{order.createdAt}</p>
      </Drawer>
      {/* 新增 */}
      <Button onClick={()=>showModal()}>新增</Button>
      <Button onClick={()=>pl()}>批量删除</Button>
 <Modal
        title={title}
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
       <Form
       form={addform}
    name="basic"
    labelCol={{ span: 8 }}
    wrapperCol={{ span: 16 }}
    style={{ maxWidth: 600 }}
    initialValues={{ remember: true }}
    onFinish={Finish}
    onFinishFailed={FinishFailed}
    autoComplete="off"
  >
    <Form.Item
      label="文章内容"
      name="title"
      rules={[{ required: true, message: 'Please input your username!' }]}
    >
      <Input />
    </Form.Item>

    <Form.Item
      label="文章标题"
      name="content"
      rules={[{ required: true, message: 'Please input your password!' }]}
    >
      <Input />
    </Form.Item>

    <Form.Item label={null}>
      <Button type="primary" htmlType="submit">
        确定
      </Button>
    </Form.Item>
  </Form>
      </Modal>
      {/* 搜索 */}
       <Form
       form={form}
       layout='inline'
    name="basic"
    style={{ maxWidth: 600 }}
    initialValues={{ remember: true }}
    onFinish={onFinish}
    onFinishFailed={onFinishFailed}
    autoComplete="off"
  >
    <Form.Item
      label="文章内容"
      name="keyword"
      // rules={[{ required: true, message: 'Please input your username!' }]}
    >
      <Input />
    </Form.Item>

    <Form.Item label={null}>
      <Button type="primary" htmlType="submit">
        搜索
      </Button>
      <Button type="primary" htmlType="submit" onClick={qinchu}>
        重置
      </Button>
    </Form.Item>
  </Form>
       <Table columns={columns} dataSource={list} rowSelection={rowSelection}
       rowKey="id"
       pagination={{
        total:85,
    showSizeChanger:true,
    showQuickJumper:true,
    showTotal:(total) => `Total ${total} items`
       }}
       />;
    </div>
  )
}

export default Index